#!/bin/bash
export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$PATH"

CHOICE=$(osascript -e 'button returned of (display dialog "Uninstall PropPairAI from this Mac?\n\n• Keep Data & Uninstall: Removes PropPairAI app, shortcuts & background service, while keeping your local property database & Excel files.\n• Delete All & Uninstall: Permanently removes PropPairAI AND deletes local database, Excel exports & Chat session." with title "Uninstall PropPairAI" buttons {"Cancel", "Keep Data & Uninstall", "Delete All & Uninstall"} default button "Keep Data & Uninstall")' 2>/dev/null || echo "Cancel")

if [ "$CHOICE" = "Cancel" ] || [ -z "$CHOICE" ]; then
  exit 0
fi

APP_DATA_DIR="$HOME/Library/Application Support/PropPairAI"
PLIST_PATH="$HOME/Library/LaunchAgents/com.proppairai.desktop.plist"

# 1. Stop LaunchAgent & any running :3000 PropPairAI process
if [ -f "$PLIST_PATH" ]; then
  launchctl unload "$PLIST_PATH" >/dev/null 2>&1 || true
  rm -f "$PLIST_PATH"
fi

PIDS=$(lsof -ti tcp:3000 2>/dev/null || true)
if [ -n "$PIDS" ]; then
  kill $PIDS >/dev/null 2>&1 || true
  sleep 1
fi
pkill -f "Application Support/PropPairAI/dist/server.mjs" >/dev/null 2>&1 || true

# 2. Remove Application & Desktop bundles
rm -rf "/Applications/PropPairAI.app" "$HOME/Applications/PropPairAI.app" "$HOME/Desktop/PropPairAI.app"

# 3. Remove runtime or entire App Support directory
if [ "$CHOICE" = "Delete All & Uninstall" ]; then
  rm -rf "$APP_DATA_DIR"
else
  rm -rf "$APP_DATA_DIR/dist" "$APP_DATA_DIR/node_modules" "$APP_DATA_DIR/bin" "$APP_DATA_DIR/logs"
  rm -f "$APP_DATA_DIR/package.json" "$APP_DATA_DIR/package-lock.json" "$APP_DATA_DIR/license_public.pem" "$APP_DATA_DIR/.env" "$APP_DATA_DIR/AppIcon.icns" "$APP_DATA_DIR/logo.png" "$APP_DATA_DIR/Uninstall PropPairAI.command"
fi

# 4. Remove Uninstaller app bundles last
(sleep 1 && rm -rf "/Applications/Uninstall PropPairAI.app" "$HOME/Applications/Uninstall PropPairAI.app") >/dev/null 2>&1 &

osascript -e 'display dialog "✅ PropPairAI has been uninstalled from your Mac." with title "PropPairAI Uninstaller" buttons {"OK"} default button "OK"' >/dev/null 2>&1 || true
exit 0
